# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = ['DataReader']

from StringIO import StringIO
import codecs

from traits.api import implements
from ..interfaces.api import IDataReader

class DataReader(object):
  implements(IDataReader)

  dataformat_id = ''
  datarepr_id = ''
  name = ''

  def __init__(self, dataformat=None, datarepr=None):
    cname = self.__class__.__name__
    if dataformat is None:
      raise ValueError, '%s will not work, dataformat=None is not valid' % (
        cname)
    elif datarepr is None :
      raise ValueError, '%s will not work, datarepr=None is not valid' % (
        cname)

    self.dataformat = dataformat
    self.datarepr = datarepr

  def toStream(self, stream):
    if isinstance(stream, (list, tuple)) :
      new_stream = StringIO()
      new_stream.write('\n'.join(stream))
      new_stream.pos = 0
    else :
      new_stream = stream
    return new_stream

  def read(self, stream):
    raise NotImplementedError

  def open(self, filepath):
    if self.dataformat.binary :
      f = open(filepath, 'rb')
    else :
      if self.dataformat.encoding :
        f = codecs.open(filepath, 'r', self.dataformat.encoding)
      else :
        f = codecs.open(filepath, 'r', u'UTF-8')
    try :
      data = self.read(f)
    except NotImplementedError :
      data = self.datarepr.new()
    f.close()
    return data
